<?php

use Illuminate\Database\Seeder;
use App\Models\Ogz;

class OgzTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //批量更新机构对应深度
        $list1 = Ogz::where(['pid'=>0])->get()->toArray();
        //默认处理4层
        foreach ($list1 as $item1) {
            //计算深度deep
            // $parents = $this->get_tree_parent($list,$item['pid']);
            // $parents =Ogz::getParent($item->pid);
            //TODO 计算ogz_ids节点
            if (Ogz::updateRow(['id',$item1['id']],['deep'=>1]) <= 0){
                \Log::info('更新ogz.deep字段失败，索引id是'.$item1['id']);
            }
            $list2 = Ogz::where(['pid'=>$item1['id']])->get()->toArray();
            foreach ($list2 as $item2) {
                if (Ogz::updateRow(['id',$item2['id']],['deep'=>2]) <= 0){
                    \Log::info('更新ogz.deep字段失败，索引id是'.$item2['id']);
                }
                $list3 = Ogz::where(['pid'=>$item2['id']])->get()->toArray();
                foreach ($list3 as $item3) {
                    if (Ogz::updateRow(['id',$item3['id']],['deep'=>3]) <= 0){
                        \Log::info('更新ogz.deep字段失败，索引id是'.$item3['id']);
                    }
                    $list4 = Ogz::where(['pid'=>$item3['id']])->get()->toArray();
                    foreach ($list4 as $item4) {
                        if (Ogz::updateRow(['id',$item4['id']],['deep'=>4]) <= 0){
                            \Log::info('更新ogz.deep字段失败，索引id是'.$item4['id']);
                        }
                    }
                }
            }
        }

    }

    function get_tree_parent($data, $id) {
        $result = array();
        $obj = array();
        foreach($data as $node) {
            $obj[$node['id']] = $node;
        }

        $value = isset($obj[$id]) ? $obj[$id] : null;
        while($value) {
            $id = null;
            foreach($data as $node) {
                if($node['id'] == $value['pid']) {
                    $id = $node['id'];
                    $result[] = $node['id'];
                    break;
                }
            }
            if($id === null) {
                $result[] = $value['pid'];
            }
            $value = isset($obj[$id]) ? $obj[$id] : null;
        }
        unset($obj);
        return $result;
    }
}
